import React, {Component} from 'react';
const TodoActions = require('../../actions/TodoActions');
const TodoStore = require('../../stores/TodoStore');

class TodoList extends Component {

  constructor(props) {
    super(props);
    this._onChange = this._onChange.bind(this);
    this._delete = this._delete.bind(this);
    this._editor = this._editor.bind(this);
    this.state = {
      infoList: TodoStore._getAll(),
      value: ''
    };
  }

  static propTypes = {

  }

  static defaultProps = {

  }

  componentDidMount() {
    TodoStore.addChangeListener(this._onChange);
  }

  componentWillUnmount() {
    TodoStore.removeChangeListener(this._onChange);
  }

  _onChange() {
    this.setState({
      infoList: TodoStore._getAll()
    });
  }

  _delete(event) {
    TodoActions._delete(event.target.getAttribute('data-index'));
  }

  _editor(event) {
    let index = event.target.getAttribute('data-index');
    let name = prompt('请输入内容', this.state.infoList[index]);

    if (name!='' && name!=null && name!=this.state.infoList[index]) {
      TodoActions._editor(index, name);
    }
  }

  render() {

    let textList = this.state.infoList.map(function(item, key) {
      return (<p key={key}>
                {item}
                <button onClick={this._delete} data-index={key}>delete</button>
                <button onClick={this._editor} data-index={key}>editor</button>
              </p>);
    }, this);

    return (
      <div className="container">
        <div>
          {textList}
        </div>
      </div>
    );
  }
}


export default TodoList;
